package com.cway;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.json.JSONObject;
import org.commonmark.node.Link;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.commonmark.node.Image;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLException;
import java.util.*;

public class Util {
    public static void main(String[] args) throws IOException, SQLException {
//        浏览器控制台header/参数转json键值对 方便直接复制为配置信息
        /*
        例如：
        Host: gitee.com
        Connection: keep-alive
        Content-Length: 65
        转换成：
        "Host": "gitee.com",
        "Connection": "keep-alive",
        "Content-Length": "65",
        适合从浏览器控制台直接复制来的header或参数，可以转换后直接在配置中使用
        * */
        String s = "";
        String replace = s.replace("\n", "\",\n\"").
                replace(": ", "\": \"");
        System.out.println("\"" + replace + "\"");
    }

    /**
     * 同上
     *
     * @param str
     * @return
     */
    public static String pairToJson(String str) {
        String replace = str.replace("\n", "\",\n\"").
                replace(": ", "\": \"");
        return "\"" + replace + "\"";
    }

    /**
     * 初始化变量储存
     * 包含date ran timestamp _
     *
     * @param config
     * @return
     */
    public static Map<String, Object> setRunMap(JSONObject config) {
        Map<String, Object> runMap = new HashMap<>();
        //        日期格式化
        String date;
        if (config.containsKey("date")) {
            date = DateUtil.format(new Date(), config.getStr("date"));
        } else {
            date = DateUtil.format(new Date(), "yyyy-MM-dd");
        }
        runMap.put("date", date);
//        随机数
        runMap.put("ran", RandomUtil.randomInt(10000, 99999));
//        时间戳
        runMap.put("timestamp", System.currentTimeMillis());
//        _变量 赋值
        for (Map.Entry<String, Object> entry : config.entrySet()) {
            if (entry.getKey().startsWith("_")) {
                runMap.put(entry.getKey().substring(1), entry.getValue());
            }
        }
        return runMap;
    }

    /**
     * ($abc)替换变量
     * 即用变量abc值替换字符串($abc)
     *
     * @param runMap
     * @param value
     * @return
     */
    public static String getDollar(Map<String, Object> runMap, String value) {
        if (!value.startsWith("$") && value.contains("($")) {
            List<String> resultFindAll = ReUtil.findAll("\\((\\$.*?)\\)", value, 1, new ArrayList<String>());
            for (String s : resultFindAll) {
                value = value.replace("(" + s + ")", runMap.get(s.substring(1)).toString());
            }
        }
        return value;
    }

    /**
     * 获取文件名 不带后缀
     *
     * @param s
     * @return
     */
    public static String getFileName(String s) {
        int index = s.lastIndexOf(".");
        return s.substring(0, index);
    }

    /**
     * markdown格式转html
     *
     * @param markdownStr
     * @return
     */
    public static String md2Html(String markdownStr) {
        Parser parser = Parser.builder().build();
        Node document = parser.parse(markdownStr);
        HtmlRenderer renderer = HtmlRenderer.builder().
                attributeProviderFactory(attributeProviderContext -> (node, s, map) -> {
                    if (node instanceof Image) {
                        map.put("style", "width:150px;height:200px;position:relative;left:50%;margin-left:-100px;");
                    }
                    if (node instanceof Link) {
                        map.put("target", "_blank");
                    }
                }).
                build();
        String mdHtml = renderer.render(document);
        return mdHtml;
    }

    /**
     * 判断是否重定向
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static Boolean isRedirectUrl(String url) {
        String redictURL = getRedirectUrl(url);
        if (redictURL == null) {
            return false;
        } else {
            return !Objects.equals(url, redictURL);
        }
    }

    /**
     * 获取重定向地址
     *
     * @param path
     * @return
     * @throws Exception
     */
    public static String getRedirectUrl(String path) {
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) new URL(path)
                    .openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setConnectTimeout(5000);
            return conn.getHeaderField("Location");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
